package cn.cdu.medical.service.impl;

import cn.cdu.medical.entity.Medicine;
import cn.cdu.medical.mapper.MedicineMapper;
import cn.cdu.medical.service.IMedicineService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 药品服务实现类
 * </p>
 */
@Slf4j
@Service
@Transactional
public class MedicineServiceImpl extends ServiceImpl<MedicineMapper, Medicine> implements IMedicineService {

    @Override
    public List<Medicine> getMedicinesByPrescriptionId(String prescriptionId) {
        log.info("查询处方药品列表, prescriptionId: {}", prescriptionId);
        LambdaQueryWrapper<Medicine> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Medicine::getId, prescriptionId);
        return list(wrapper);
    }

    @Override
    public List<Medicine> searchMedicinesByName(String name) {
        if (StringUtils.isBlank(name)) {
            return new ArrayList<>();
        }

        String searchTerm = "%" + name.trim() + "%";
        
        // 使用LambdaQueryWrapper进行模糊搜索
        LambdaQueryWrapper<Medicine> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.and(wrapper -> wrapper
                .like(Medicine::getName, searchTerm)
                .or()
                .like(Medicine::getCategory, searchTerm)
                .or()
                .like(Medicine::getManufacturer, searchTerm));
        
        // 添加排序和限制
        queryWrapper.orderByDesc(Medicine::getStock)
                   .orderByAsc(Medicine::getName)
                   .last("LIMIT 20");  // 限制返回结果数量，提高性能

        List<Medicine> medicines = baseMapper.selectList(queryWrapper);
        log.info("搜索药品完成, 关键词: {}, 结果数量: {}", name, medicines.size());
        return medicines;
    }

    @Override
    public List<Medicine> getFrequentMedicines() {
        log.info("获取常用药品列表");
        // 这里可以根据实际业务需求修改查询条件
        // 例如：根据使用频率、库存量等条件查询
        LambdaQueryWrapper<Medicine> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Medicine::getStock) // 按库存量降序
              .last("LIMIT 16"); // 限制返回10条记录
        return list(wrapper);
    }
} 